package com.xiaoshuidi.cloud.module.finance.service.finance.impl;


import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.framework.common.exception.ServiceException;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.contract.enums.ErrorCodeConstants;
import com.xiaoshuidi.cloud.module.finance.controller.admin.finance.vo.account.WorkbenchFinanceTotalResp;
import com.xiaoshuidi.cloud.module.finance.dal.mysql.finance.FinanceMoneyFlowMapper;
import com.xiaoshuidi.cloud.module.finance.service.finance.WorkbenchTotalService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class WorkbenchServiceImpl implements WorkbenchTotalService {

//    private final Long KEY_EXPIRE= 3000l;

    private final FinanceMoneyFlowMapper financeMoneyFlowMapper;
    private final RedisTemplate redisTemplate;

    @Override
    public WorkbenchFinanceTotalResp getTotal(Long apartmentId) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(ErrorCodeConstants.USER_NOT_LOGIN);
        }
        Long tenantId = loginUser.getTenantId();
        try {
            Object json =  redisTemplate.opsForValue().get("finance_"+apartmentId+"_"+tenantId);
            if(json==null){
                return getWorkbenchTotalResp(tenantId,apartmentId);
            }else {
                 return JSONObject.parseObject((String)json, WorkbenchFinanceTotalResp.class);
            }
        } catch (Exception e) {
            log.error("====== 获取页面总数据异常{}",e.getMessage());
            return getWorkbenchTotalResp(tenantId,apartmentId);
        }
    }

    @NotNull
    private WorkbenchFinanceTotalResp getWorkbenchTotalResp(Long tenantId,Long apartmentId) {
        //查询今日现金收入
        WorkbenchFinanceTotalResp resp = new WorkbenchFinanceTotalResp();
        BigDecimal todayIncome= financeMoneyFlowMapper.sumTodayIncome(tenantId,apartmentId);
        BigDecimal cashInToday= financeMoneyFlowMapper.sumTodayCashIncome(tenantId,apartmentId);
        resp.setCashInToday(cashInToday);
        resp.setTotalInToday(todayIncome);
        //应收未收 账单状态应收款和已逾期，未支付总金额
        resp.setTotalInCurrentMonth(financeMoneyFlowMapper.sumTotalInCurrentMonth(tenantId,apartmentId));
        resp.setTotalInCurrentYear(financeMoneyFlowMapper.sumTotalInCurrentYear(tenantId,apartmentId));
//        redisTemplate.opsForValue().setIfAbsent("finance_"+apartmentId+"_"+tenantId.toString(), JSONObject.toJSONString(resp),KEY_EXPIRE, TimeUnit.SECONDS);
        return resp;
    }
}
